package kr.ac.kaist.simplefileexplorer;

import java.util.ArrayList;
import java.util.List;

import kr.ac.kaist.simplefileexplorer.connection.ContactCloudClient;
import kr.ac.kaist.simplefileexplorer.entity.ShareRequestEntity;
import kr.ac.kaist.simplefileexplorer.util.ContactUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SeeSharedActivity extends Activity {

	private ListView __sharedFileList = null;

	private final String SEE_SHARE_ACTIVITY_TAG = "SeeSharedActivity";

	private ArrayAdapter<ShareRequestEntity> __fileArrayAdapter;

	private String __myPhoneNumber = "";

	private DownloadManager __downloadManager = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_file_list);

		__downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

		__sharedFileList = (ListView) findViewById(R.id.file_list);
		__sharedFileList.setOnItemClickListener(onItemClickListener);

		__myPhoneNumber = ContactUtil.getMyPhoneNumber(this);
		GetHttpTask task = new GetHttpTask();
		task.execute(__myPhoneNumber);
		
		IntentFilter completeFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
		registerReceiver(completeReceiver, completeFilter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.service_select, menu);
		return true;
	}

	class GetHttpTask extends
			AsyncTask<String, Void, ArrayList<ShareRequestEntity>> {

		protected ArrayList<ShareRequestEntity> doInBackground(String... params) {
			ArrayList<ShareRequestEntity> resultList = ContactCloudClient
					.getSharedFile(params[0]);
			Log.i(SEE_SHARE_ACTIVITY_TAG, "List Count: " + resultList.size());

			return resultList;
		}

		// Called by main thread.
		protected void onPostExecute(ArrayList<ShareRequestEntity> result) {

			int listCount = result.size();
			String message = "Total files(" + listCount + ")";

			Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT)
					.show();

			showList(result);
		}
	}

	public void showList(ArrayList<ShareRequestEntity> result) {
		__fileArrayAdapter = new FileArrayAdapter(this, R.layout.file_list_entry,
				result);
		__sharedFileList.setAdapter(__fileArrayAdapter);
		__fileArrayAdapter.notifyDataSetChanged();
	}

	private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int pos,
				long id) {

			final ShareRequestEntity entity = __fileArrayAdapter.getItem(pos);
			final String cloudFileUrl = entity.getCloudFileUrl();
			
			int downloadLimit = Integer.parseInt(entity.getDownloadLimit());
			
			if (downloadLimit > 0)
				entity.setDownloadLimit(String.valueOf(--downloadLimit));	

			Uri urlToDownload = Uri.parse(cloudFileUrl);
			List<String> pathSegments = urlToDownload.getPathSegments();
			DownloadManager.Request request = new DownloadManager.Request(
					urlToDownload);
			request.setTitle(entity.getTitleOfFile());
			request.setDescription("");

			String downloadDir = Environment.DIRECTORY_DOWNLOADS;

			request.setDestinationInExternalPublicDir(
					Environment.DIRECTORY_DOWNLOADS,
					pathSegments.get(pathSegments.size() - 1));
			Environment.getExternalStoragePublicDirectory(
					Environment.DIRECTORY_DOWNLOADS).mkdirs();

			long latestId = __downloadManager.enqueue(request);
		}
	};

	private BroadcastReceiver completeReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			Toast.makeText(context, "Download Complete!", Toast.LENGTH_SHORT)
					.show();
			
			__fileArrayAdapter.notifyDataSetChanged();

			startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
		}

	};

	private class FileArrayAdapter extends ArrayAdapter<ShareRequestEntity> {
		private ArrayList<ShareRequestEntity> items;
		private int rsrc;

		public FileArrayAdapter(Context ctx, int rsrcId,
				ArrayList<ShareRequestEntity> data) {
			super(ctx, rsrcId, data);
			this.items = data;
			this.rsrc = rsrcId;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(rsrc, null);
			}

			ShareRequestEntity entity = items.get(position);
			if (entity != null) {
	
				((TextView) v.findViewById(R.id.fileName)).setText(entity
						.getTitleOfFile());

				((TextView) v.findViewById(R.id.dueDate)).setText(entity
						.getDueDate());
				((TextView) v.findViewById(R.id.downloadLimit)).setText(entity
						.getDownloadLimit());

				if (entity.getContacts().indexOf(__myPhoneNumber) != -1) {				

					((ImageView) v.findViewById(R.id.ePhoto))
							.setImageResource(R.drawable.download);
					
					((TextView) v.findViewById(R.id.sender)).setText(entity
							.getMyContact());
				} else {
					((ImageView) v.findViewById(R.id.ePhoto))
							.setImageResource(R.drawable.upload);
					
					((TextView) v.findViewById(R.id.sender)).setText(entity
							.getContacts());
				}
			}
			return v;
		}
	}

}
